<template>
    
    <view>
        <navigation-bar :back="true" title="搜索游戏"></navigation-bar>

        <view style="display: flex; width: auto">
            <view
                @tap="goToSearch"
                style="position: relative; width: auto; background: #eee; height: 66rpx; border-radius: 100rpx; padding: 0 30rpx; margin: 0 20rpx; line-height: 66rpx; flex: 1"
            >
                <input style="height: inherit; margin-left: 35rpx" placeholder="搜索" @input="onChange" :value="searchText" />
                <image src="/static/images/search.png" style="position: absolute; width: 32rpx; height: 32rpx; top: 17rpx; left: 20rpx"></image>
            </view>
            <view slot="action" @tap="onSearch" class="search">搜索</view>
        </view>

        <view class="search1" v-if="searchText.length == 0">
            <view class="search2">
                <view class="search3">搜索历史</view>
                <view class="search4">
                    <image src="/static/images/delete.png" class="search5" @tap="deleteHistory"></image>
                </view>
            </view>
            <view class="search6">
                <view class="search8" @tap="fastSearch" :data-data="item" v-for="(item, index) in historyData" :key="index">{{ item }}</view>
            </view>
        </view>

        <view class="search1" v-if="searchText.length == 0">
            <view class="search2">
                <view class="search3">猜你想搜</view>
                <view class="search4">
                    <image src="/static/images/refresh.png" class="search5" style="width: 32rpx; height: 32rpx; padding-right: 1rpx" @tap="getRandomGame"></image>
                </view>
            </view>
            <view class="search6">
                <view class="search8" @tap="fastSearch" :data-data="item.appname" v-for="(item, index) in cainiGame" :key="index">{{ item.appname }}</view>
            </view>
        </view>

        <view class="t111" v-if="searchText.length != 0">
            <scroll-view scroll-y class="scrollView" :refresher-triggered="isUp" @scrolltolower="down" :lower-threshold="80">
                <view class="t11" v-for="(item, index) in gameData" :key="index">
                    <view class="t12">
                        <view class="t13">
                            <image :src="item.logoSquare" mode="" class="t14" />
                        </view>
                        <view class="t15">
                            <rich-text class="t16" :nodes="item.appname"></rich-text>
                            <rich-text class="t17" :nodes="item.briefIntro"></rich-text>
                            <view class="t18">
                                <view class="t19">{{ item.clickCount ? item.clickCount / 16 + '万+玩过' : '0人玩过' }}</view>
                                <view class="t20"></view>
                                <view class="t19">{{ item.category2Name }}</view>
                                <view class="t20"></view>
                                <view class="t19">{{ item.category3Name }}</view>
                            </view>
                        </view>
                        <view class="t21">
                            <view class="t22" @tap="goToGame" :data-data="item">秒玩</view>
                        </view>
                    </view>
                </view>
                <view v-if="isClick && gameData.length == 0" style="text-align: center; color: gray; margin-top: 55rpx">搜索暂无相关游戏</view>
                <view
                    v-if="gameData.length % limit != 0"
                    style="margin-right: 145rpx; margin-left: 115rpx; text-align: center; color: var(--GColor); display: flex; align-items: center"
                >
                    <view style="height: 2rpx; background-color: #ddd; flex: 1"></view>
                    <view style="padding: 0 15rpx">没有更多了</view>
                    <view style="height: 2rpx; background-color: #ddd; flex: 1"></view>
                </view>
                <view style="height: 50rpx"></view>
            </scroll-view>
        </view>
        <!-- 添加自定义登录提示框 -->
		<CustomConfirm
			:visible.sync="showLoginConfirm"
			title="温馨提示"
			content="亲，您还没登录，请先登录~"
			@confirm="handleLoginConfirm"
			@cancel="handleLoginCancel"
		/>
    </view>
</template>

<script>
import navigationBar from '../../components/navigation-bar/navigation-bar.vue';
import CustomConfirm from '../../components/CustomConfirm/CustomConfirm.vue';
import loginStatusUtils from '../../utils/loginStatusUtils';
import { getGame, addClick, addOpen } from '../../api/getApi';
import { addMyGame } from '../../api/userGameApi';
import { cleanHtml } from '../../utils/htmlUtils';
export default {
    components: {
        navigationBar
    },
    data() {
        return {
            showLoginConfirm: false,//登录提示框是否显示
            searchText: '',
            gameData: [],
            cainiGame: [],
            historyData: uni.getStorageSync('historyData') ? JSON.parse(uni.getStorageSync('historyData')) : [],
            isClick: false,
            page: 1,
            limit: 25,
            myGame: '',
            isUp: false
        };
    },
    onLoad(options) {
        this.getRandomGame();
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.setData({
            historyData: uni.getStorageSync('historyData') ? JSON.parse(uni.getStorageSync('historyData')) : []
        });
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {},
    methods: {
        onSearch(e) {
            this.setData({
                gameData: [],
                page: 1,
                isClick: true
            });
            let historyData = uni.getStorageSync('historyData') ? JSON.parse(uni.getStorageSync('historyData')) : [];
            if (!historyData.find((v) => v === this.searchText) && this.searchText.length > 0) {
                historyData = [this.searchText, ...historyData];
                uni.setStorageSync('historyData', JSON.stringify(historyData));
                this.setData({
                    historyData: historyData
                });
            }
            if (this.searchText.length > 0) {
                this.getData();
            }
        },

        onChange(e) {
            console.log(e);
            this.setData({
                searchText: e.detail.value
            });
            if (!this.searchText || this.searchText.length == 0) {
                this.setData({
                    isClick: false,
                    page: 1,
                    gameData: []
                });
            }
        },

        down(e) {
            this.setData({
                page: this.page + 1
            });
            this.getData();
        },

        getData() {
            getGame({
                page: this.page,
                limit: this.limit,
                appname: this.searchText,
                briefIntro: this.searchText,
                searchAll: 'true'
            }).then((res) => {
                const list = res.data.list;
                if (list && list.length > 0) {
                    const resultList = list.map((item) => {
                        const appnameHighlighted = this.highlightText(item.appname, this.searchText);
                        const briefIntroHighlighted = this.highlightText(item.briefIntro, this.searchText);
                        return {
                            ...item,
                            appname: appnameHighlighted,
                            briefIntro: briefIntroHighlighted
                        };
                    });
                    this.setData({
                        gameData: [...this.gameData, ...resultList]
                    });
                }
            });
        },

        highlightText(text, keyword) {
            if (!keyword) {
                return text;
            }
            const reg = new RegExp(keyword, 'gi');
            return text.replace(reg, `<span class="highlight">${keyword}</span>`);
        },

        /* goToGame(e) {
            let itemdata = e.currentTarget.dataset.data;
            if (itemdata.appid) {
                uni.navigateToMiniProgram({
                    appId: itemdata.appid,
                    path: '?wxgamepro=CpsCBgAAoXkpQY9UXS9__OwV',
                    envVersion: 'release',
                    success: (res) => {
                        let myGame = uni.getStorageSync('myGame');
                        if (!myGame) {
                            myGame = [];
                        } else {
                            myGame = JSON.parse(myGame).slice(0, 300);
                        }
                        if (!myGame.find((v) => v.id === itemdata.id)) {
                            myGame = [itemdata, ...myGame];
                        }
                        uni.setStorageSync('myGame', JSON.stringify(myGame));
                        this.setData({
                            myGame: myGame
                        });
                        addOpen({
                            id: itemdata.id
                        });
                    }
                });
                addClick({
                    id: itemdata.id
                });
            } else {
                uni.showToast({
                    title: `尊敬的大人对对不不起起！此游戏出了点小问题~`,
                    icon: 'none'
                });
            }
        }, */


        goToGame(e) {
            // 检查登录状态
			if (!loginStatusUtils.checkLoginAndShowConfirm(this)) {
				return;
			}
			let itemdata = e.currentTarget.dataset.data;
			let loginType = 'app';

            // console.log('itemdata',itemdata);

            let cleanAppname = cleanHtml(itemdata.appname);
            let cleanUrl = cleanHtml(itemdata.gameUrl);

            //加入我的游戏
			addMyGame({
				kyyGameId:itemdata.id,
				// kyyGameAppname:itemdata.appname,
				kyyGameAppname:cleanAppname,
				kyyGameLogo:itemdata.logo,
				// kyyGameUrl:itemdata.gameUrl
				kyyGameUrl:cleanUrl
			}).then(res => {
				console.log('成功加入我的游戏',res);
			});

			//处于微信端时
			if (itemdata.appid && loginType === 'weixin') {
				uni.navigateToMiniProgram({
					appId: itemdata.appid,
					path: '?wxgamepro=CpsCBgAAoXkpQY9UXS9__OwV',
					envVersion: 'release',
					success: (res) => {
						let myGame = uni.getStorageSync('myGame');
						if (!myGame) {
							myGame = [];
						} else {
							myGame = JSON.parse(myGame).slice(0, 300);
						}
						if (!myGame.find((v) => v.id === itemdata.id)) {
							myGame = [itemdata, ...myGame];
						}
						uni.setStorageSync('myGame', JSON.stringify(myGame));
						this.setData({
							myGame: myGame
						});
						addOpen({
							id: itemdata.id
						});
					}
				});
				addClick({
					id: itemdata.id
				});
			}
			//处于APP端时
			else if (itemdata.userName && loginType === 'app') {
				uni.showToast({
					title: `现在处于APP端,正在为您打开游戏，请稍等~`,
					icon: 'none',
				}); 
                
				
				//跳进外部浏览器打开微信小游戏
				/* plus.runtime.openURL(itemdata.gameUrl, function(res) {
					console.log(res);
				}); */

				//跳进内嵌浏览器webview打开微信小游戏
				//对url进行编码
				let encodedUrl = encodeURIComponent(itemdata.gameUrl);
				addClick({
					id: itemdata.id
				});
				uni.navigateTo({
					url: `/pages/webview/webview?src=${encodedUrl}&title=${itemdata.appname}`,
				}).then(res => {
					// console.log('跳转成功', res);
					addOpen({
						id: itemdata.id
					});
				}).catch(err => {
					console.error('跳转失败', err);
				});
				
				
				
				
				
				//从微信小程序进入跳进，目前只能跳进首页
				/* this.sweixin.launchMiniProgram({
					id: 'gh_f03eb6ba7bc9', //要跳转小程序的原始ID
					// path: `pages/tslogin/tslogin?do=login&appName=${itemdata.username}`, //  可带参数
					// path: `https://game.weixin.qq.com/cgi-bin/comm/openlink?auth_appid=wx62d9035fd4fd2059&url=https%3A%2F%2Fgame.weixin.qq.com%2Fcgi-bin%2Fminigame%2Fstatic%2Fcps-transfer%2Findex.html%3Ft%3DAARwtQwFAAABAAAAAACb5dZ3Bq27t3udXwPJZxAAAADA8RG5WEKQmoqKviNESI_t_xpcTGNZbOvZhGLbF_si_gri_9qdvru4eA8jre-QDluA9gJxhZESxT4o%26wechat_pkgid%3Dminigame__cps_transfer_index`, //  可带参数
					success: (res) => {
						console.log('跳转成功', res);
					},
					fail: (err) => {
						console.error('跳转失败', err);
					}
				})
				 */
				
			} 

			else {
				uni.showToast({
					title: `尊敬的大人对对不不起起！此游戏出了点小问题~`,
					icon: 'none'
				});
			}
		},

        //点击立即搜索
        fastSearch(e) {
            this.setData({
                gameData: [],
                page: 1,
                isClick: true,
                searchText: e.currentTarget.dataset.data
            });
            let historyData = uni.getStorageSync('historyData') ? JSON.parse(uni.getStorageSync('historyData')) : [];
            if (!historyData.find((v) => v === this.searchText)) {
                historyData = [this.searchText, ...historyData];
                uni.setStorageSync('historyData', JSON.stringify(historyData));
                this.setData({
                    historyData: historyData
                });
            }
            if (this.searchText.length > 0) {
                this.getData();
            }
        },

        getRandomGame() {
            getGame({
                page: 1,
                limit: 10,
                randomGame: 'true'
            }).then((res) => {
                this.setData({
                    cainiGame: res.data.list
                });
            });
        },

        deleteHistory() {
            let data = [];
            uni.setStorageSync('historyData', JSON.stringify(data));
            this.setData({
                historyData: []
            });
        },

        goToSearch() {
            console.log('占位：函数 goToSearch 未声明');
        },
        //登录提示框确认事件
		handleLoginConfirm() {
			uni.navigateTo({
				// 跳进登录页面
				url: '/pages/login/login'
			});
		},
		//登录提示框取消事件
		handleLoginCancel() {
			this.showLoginConfirm = false;
		}
    }
};
</script>
<style>
.search {
    background-color: rgba(var(--red), var(--green), var(--blue), 0.15);
    color: var(--Color);
    border-radius: 30rpx;
    margin: 0 25rpx;
    padding: 0 30rpx;
    border: 1rpx solid var(--Color);
    height: 55rpx;
    line-height: 55rpx;
}

.t111 {
    display: flex;
    padding: 25rpx 0rpx 0 30rpx;
    height: inherit;
    flex-direction: column;
    overflow: hidden;
}

.t11 {
    display: flex;
    width: 100%;
    flex-direction: column;
    margin-top: 10rpx;
    margin-bottom: 30rpx;
}
.t11:last-child {
    margin-bottom: 130rpx;
}
.t12 {
    display: flex;
    width: 100%;
}

.t13 {
    display: flex;
    margin-right: 30rpx;
}

.t14 {
    width: 120rpx;
    height: 120rpx;
    border-radius: 28rpx;
}

.t15 {
}

.t16 {
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    font-size: 30rpx;
    font-weight: 600;
}

.t17 {
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    font-size: 24rpx;
    color: gray;
    padding-top: 10rpx;
}

.t18 {
    display: flex;
    font-size: 24rpx;
    color: gray;
    align-items: center;
    padding-top: 10rpx;
}

.t19 {
}

.t20 {
    background: gray;
    width: 0;
    height: 22rpx;
    margin: 0 10rpx;
}

.t21 {
    word-break: keep-all;
    display: flex;
    align-items: center;
    margin-left: 30rpx;
    flex: 1;
    justify-content: flex-end;
}

.t22 {
    margin-right: 30rpx;
    height: 50rpx;
    background: rgba(var(--Gred), var(--Ggreen), var(--Gblue), 0.15);
    text-align: center;
    line-height: 50rpx;
    padding: 5rpx 35rpx;
    border-radius: 100rpx;
    font-size: 26rpx;
    color: var(--Color);
    font-weight: bold;
}

.line {
    width: auto;
    height: 2rpx;
    background: rgba(var(--Gred), var(--Ggreen), var(--Gblue), 0.25);
    margin: 30rpx 30rpx 30rpx 120rpx;
}

.scrollView {
    overflow: auto;
}

.highlight {
    color: var(--Color);
    font-weight: bold;
}

.search1 {
    padding: 20rpx 30rpx;
}
.search2 {
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.search3 {
    font-weight: 700;
    font-size: 36rpx;
    color: #000000;
    line-height: 56rpx;
}
.search4 {
}
.search5 {
    width: 40rpx;
    height: 40rpx;
}
.search6 {
    display: flex;
    align-items: baseline;
    flex-wrap: wrap;
    padding-top: 20rpx;
}
.search7 {
    background: white;
    border: 1px solid #eee;
    border-radius: 100rpx;
    width: max-content;
    padding: 13rpx 28rpx;
    color: gray;
    margin-bottom: 10rpx;
    margin-right: 20rpx;
    font-size: 24rpx;
}
.search8 {
    background: #ededed;
    border-radius: 10rpx;
    width: max-content;
    padding: 13rpx 28rpx;
    color: black;
    font-size: 24rpx;
    margin: 0 18rpx 18rpx 0;
}
</style>
